package com.spring.lo.framework.factory.support;

import com.spring.lo.framework.factory.ListableBeanFactory;
import com.spring.lo.framework.factory.config.BeanDefinition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ListableBeanFactory的默认实现
 * 不需要实现太多功能，却BeanFactory的所有功能
 * @author zhangbh
 * 2023-05-28 16:45
 **/
public class DefaultListableBeanFactory extends AbstractAutowiredCapableBeanFactory implements BeanDefinitionRegistry, ListableBeanFactory {


    /**
     * 存放Bean元信息对应关系
     * key=beanName,value=BeanDefinition
     */
    private Map<String, BeanDefinition> beanDefinitions = new HashMap<>();

    @Override
    public List<Object> getBeansByType(Class<?> clazz) {
        List<Object> beans = new ArrayList<>();
        List<BeanDefinition> bds = getBeanDefinitions();
        for (BeanDefinition bd : bds) {
            if (clazz.isAssignableFrom(bd.getClassType())) {
                beans.add(getBean(bd.getBeanName()));
            }
        }
        return beans;
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitions.put(beanName, beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        return beanDefinitions.get(beanName);
    }

    @Override
    public List<BeanDefinition> getBeanDefinitions() {
        List<BeanDefinition> bds = new ArrayList<>(beanDefinitions.size());
        for (Map.Entry<String, BeanDefinition> stringBeanDefinitionEntry : beanDefinitions.entrySet()) {
            bds.add(stringBeanDefinitionEntry.getValue());
        }
        return bds;
    }
}
